{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5f93b7d1",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/zhy/anaconda3/envs/mathglm/lib/python3.9/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "from transformers import AutoModelForSeq2SeqLM\n",
    "from peft import get_peft_config, get_peft_model, get_peft_model_state_dict, LoraConfig, TaskType\n",
    "import torch\n",
    "from datasets import load_dataset\n",
    "import os\n",
    "\n",
    "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
    "from transformers import AutoTokenizer\n",
    "from torch.utils.data import DataLoader\n",
    "from transformers import default_data_collator, get_linear_schedule_with_warmup\n",
    "from tqdm import tqdm\n",
    "from datasets import load_dataset\n",
    "\n",
    "device = \"cuda\"\n",
    "model_name_or_path = \"bigscience/mt0-small\"\n",
    "tokenizer_name_or_path = \"bigscience/mt0-small\"\n",
    "\n",
    "checkpoint_name = \"financial_sentiment_analysis_lora_v1.pt\"\n",
    "text_column = \"sentence\"\n",
    "label_column = \"text_label\"\n",
    "max_length = 128\n",
    "lr = 1e-3\n",
    "num_epochs = 3\n",
    "batch_size = 8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8d0850ac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "trainable params: 362,496 || all params: 300,539,264 || trainable%: 0.1206\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "PeftModelForSeq2SeqLM(\n",
       "  (base_model): LoraModel(\n",
       "    (model): MT5ForConditionalGeneration(\n",
       "      (shared): Embedding(250112, 512)\n",
       "      (encoder): MT5Stack(\n",
       "        (embed_tokens): Embedding(250112, 512)\n",
       "        (block): ModuleList(\n",
       "          (0): MT5Block(\n",
       "            (layer): ModuleList(\n",
       "              (0): MT5LayerSelfAttention(\n",
       "                (SelfAttention): MT5Attention(\n",
       "                  (q): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (k): Linear(in_features=512, out_features=384, bias=False)\n",
       "                  (v): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (o): Linear(in_features=384, out_features=512, bias=False)\n",
       "                  (relative_attention_bias): Embedding(32, 6)\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "              (1): MT5LayerFF(\n",
       "                (DenseReluDense): MT5DenseGatedActDense(\n",
       "                  (wi_0): Linear(in_features=512, out_features=1024, bias=False)\n",
       "                  (wi_1): Linear(in_features=512, out_features=1024, bias=False)\n",
       "                  (wo): Linear(in_features=1024, out_features=512, bias=False)\n",
       "                  (dropout): Dropout(p=0.1, inplace=False)\n",
       "                  (act): NewGELUActivation()\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (1-7): 7 x MT5Block(\n",
       "            (layer): ModuleList(\n",
       "              (0): MT5LayerSelfAttention(\n",
       "                (SelfAttention): MT5Attention(\n",
       "                  (q): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (k): Linear(in_features=512, out_features=384, bias=False)\n",
       "                  (v): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (o): Linear(in_features=384, out_features=512, bias=False)\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "              (1): MT5LayerFF(\n",
       "                (DenseReluDense): MT5DenseGatedActDense(\n",
       "                  (wi_0): Linear(in_features=512, out_features=1024, bias=False)\n",
       "                  (wi_1): Linear(in_features=512, out_features=1024, bias=False)\n",
       "                  (wo): Linear(in_features=1024, out_features=512, bias=False)\n",
       "                  (dropout): Dropout(p=0.1, inplace=False)\n",
       "                  (act): NewGELUActivation()\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "        )\n",
       "        (final_layer_norm): MT5LayerNorm()\n",
       "        (dropout): Dropout(p=0.1, inplace=False)\n",
       "      )\n",
       "      (decoder): MT5Stack(\n",
       "        (embed_tokens): Embedding(250112, 512)\n",
       "        (block): ModuleList(\n",
       "          (0): MT5Block(\n",
       "            (layer): ModuleList(\n",
       "              (0): MT5LayerSelfAttention(\n",
       "                (SelfAttention): MT5Attention(\n",
       "                  (q): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (k): Linear(in_features=512, out_features=384, bias=False)\n",
       "                  (v): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (o): Linear(in_features=384, out_features=512, bias=False)\n",
       "                  (relative_attention_bias): Embedding(32, 6)\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "              (1): MT5LayerCrossAttention(\n",
       "                (EncDecAttention): MT5Attention(\n",
       "                  (q): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (k): Linear(in_features=512, out_features=384, bias=False)\n",
       "                  (v): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (o): Linear(in_features=384, out_features=512, bias=False)\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "              (2): MT5LayerFF(\n",
       "                (DenseReluDense): MT5DenseGatedActDense(\n",
       "                  (wi_0): Linear(in_features=512, out_features=1024, bias=False)\n",
       "                  (wi_1): Linear(in_features=512, out_features=1024, bias=False)\n",
       "                  (wo): Linear(in_features=1024, out_features=512, bias=False)\n",
       "                  (dropout): Dropout(p=0.1, inplace=False)\n",
       "                  (act): NewGELUActivation()\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "          (1-7): 7 x MT5Block(\n",
       "            (layer): ModuleList(\n",
       "              (0): MT5LayerSelfAttention(\n",
       "                (SelfAttention): MT5Attention(\n",
       "                  (q): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (k): Linear(in_features=512, out_features=384, bias=False)\n",
       "                  (v): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (o): Linear(in_features=384, out_features=512, bias=False)\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "              (1): MT5LayerCrossAttention(\n",
       "                (EncDecAttention): MT5Attention(\n",
       "                  (q): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (k): Linear(in_features=512, out_features=384, bias=False)\n",
       "                  (v): lora.Linear(\n",
       "                    (base_layer): Linear(in_features=512, out_features=384, bias=False)\n",
       "                    (lora_dropout): ModuleDict(\n",
       "                      (default): Identity()\n",
       "                    )\n",
       "                    (lora_A): ModuleDict(\n",
       "                      (default): Linear(in_features=512, out_features=8, bias=False)\n",
       "                    )\n",
       "                    (lora_B): ModuleDict(\n",
       "                      (default): Linear(in_features=8, out_features=384, bias=False)\n",
       "                    )\n",
       "                    (lora_embedding_A): ParameterDict()\n",
       "                    (lora_embedding_B): ParameterDict()\n",
       "                    (lora_magnitude_vector): ModuleDict(\n",
       "                      (default): lora.dora.DoraLinearLayer()\n",
       "                    )\n",
       "                  )\n",
       "                  (o): Linear(in_features=384, out_features=512, bias=False)\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "              (2): MT5LayerFF(\n",
       "                (DenseReluDense): MT5DenseGatedActDense(\n",
       "                  (wi_0): Linear(in_features=512, out_features=1024, bias=False)\n",
       "                  (wi_1): Linear(in_features=512, out_features=1024, bias=False)\n",
       "                  (wo): Linear(in_features=1024, out_features=512, bias=False)\n",
       "                  (dropout): Dropout(p=0.1, inplace=False)\n",
       "                  (act): NewGELUActivation()\n",
       "                )\n",
       "                (layer_norm): MT5LayerNorm()\n",
       "                (dropout): Dropout(p=0.1, inplace=False)\n",
       "              )\n",
       "            )\n",
       "          )\n",
       "        )\n",
       "        (final_layer_norm): MT5LayerNorm()\n",
       "        (dropout): Dropout(p=0.1, inplace=False)\n",
       "      )\n",
       "      (lm_head): Linear(in_features=512, out_features=250112, bias=False)\n",
       "    )\n",
       "  )\n",
       ")"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# creating model\n",
    "peft_config = LoraConfig(task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, use_dora=True)\n",
    "\n",
    "model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)\n",
    "model = get_peft_model(model, peft_config)\n",
    "model.print_trainable_parameters()\n",
    "model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4ee2babf",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Map: 100%|██████████| 2037/2037 [00:00<00:00, 107797.29 examples/s]\n",
      "Map: 100%|██████████| 227/227 [00:00<00:00, 83226.14 examples/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'sentence': \"Under the transaction agreement , Metsaliitto will purchase 24.7 % of Metsa-Botnia 's shares from UPM and 3 % from M-real .\",\n",
       " 'label': 1,\n",
       " 'text_label': 'neutral'}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# loading dataset\n",
    "dataset = load_dataset(\"financial_phrasebank\", \"sentences_allagree\")\n",
    "dataset = dataset[\"train\"].shuffle(64).train_test_split(test_size=0.1)\n",
    "dataset[\"validation\"] = dataset[\"test\"]\n",
    "del dataset[\"test\"]\n",
    "\n",
    "classes = dataset[\"train\"].features[\"label\"].names\n",
    "dataset = dataset.map(\n",
    "    lambda x: {\"text_label\": [classes[label] for label in x[\"label\"]]},\n",
    "    batched=True,\n",
    "    num_proc=1,\n",
    ")\n",
    "\n",
    "dataset[\"train\"][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "adf9608c",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/zhy/anaconda3/envs/mathglm/lib/python3.9/site-packages/transformers/tokenization_utils_base.py:1601: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be depracted in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n",
      "  warnings.warn(\n",
      "Running tokenizer on dataset: 100%|██████████| 2037/2037 [00:00<00:00, 10738.99 examples/s]\n",
      "Running tokenizer on dataset: 100%|██████████| 227/227 [00:00<00:00, 8477.72 examples/s]\n"
     ]
    }
   ],
   "source": [
    "# data preprocessing\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)\n",
    "\n",
    "\n",
    "def preprocess_function(examples):\n",
    "    inputs = examples[text_column]\n",
    "    targets = examples[label_column]\n",
    "    model_inputs = tokenizer(inputs, max_length=max_length, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n",
    "    labels = tokenizer(targets, max_length=3, padding=\"max_length\", truncation=True, return_tensors=\"pt\")\n",
    "    labels = labels[\"input_ids\"]\n",
    "    labels[labels == tokenizer.pad_token_id] = -100\n",
    "    model_inputs[\"labels\"] = labels\n",
    "    return model_inputs\n",
    "\n",
    "\n",
    "processed_datasets = dataset.map(\n",
    "    preprocess_function,\n",
    "    batched=True,\n",
    "    num_proc=1,\n",
    "    remove_columns=dataset[\"train\"].column_names,\n",
    "    load_from_cache_file=False,\n",
    "    desc=\"Running tokenizer on dataset\",\n",
    ")\n",
    "\n",
    "train_dataset = processed_datasets[\"train\"]\n",
    "eval_dataset = processed_datasets[\"validation\"]\n",
    "\n",
    "train_dataloader = DataLoader(\n",
    "    train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True\n",
    ")\n",
    "eval_dataloader = DataLoader(eval_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f733a3c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# optimizer and lr scheduler\n",
    "optimizer = torch.optim.AdamW(model.parameters(), lr=lr)\n",
    "lr_scheduler = get_linear_schedule_with_warmup(\n",
    "    optimizer=optimizer,\n",
    "    num_warmup_steps=0,\n",
    "    num_training_steps=(len(train_dataloader) * num_epochs),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6b3a4090",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 255/255 [00:09<00:00, 26.32it/s]\n",
      "100%|██████████| 29/29 [00:00<00:00, 63.62it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=0: train_ppl=tensor(2.7751, device='cuda:0') train_epoch_loss=tensor(1.0207, device='cuda:0') eval_ppl=tensor(1.2535, device='cuda:0') eval_epoch_loss=tensor(0.2260, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 255/255 [00:09<00:00, 27.34it/s]\n",
      "100%|██████████| 29/29 [00:00<00:00, 64.57it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=1: train_ppl=tensor(1.3024, device='cuda:0') train_epoch_loss=tensor(0.2642, device='cuda:0') eval_ppl=tensor(1.1924, device='cuda:0') eval_epoch_loss=tensor(0.1759, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 255/255 [00:09<00:00, 27.68it/s]\n",
      "100%|██████████| 29/29 [00:00<00:00, 64.50it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch=2: train_ppl=tensor(1.2315, device='cuda:0') train_epoch_loss=tensor(0.2082, device='cuda:0') eval_ppl=tensor(1.1667, device='cuda:0') eval_epoch_loss=tensor(0.1542, device='cuda:0')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "# training and evaluation\n",
    "model = model.to(device)\n",
    "\n",
    "for epoch in range(num_epochs):\n",
    "    model.train()\n",
    "    total_loss = 0\n",
    "    for step, batch in enumerate(tqdm(train_dataloader)):\n",
    "        batch = {k: v.to(device) for k, v in batch.items()}\n",
    "        outputs = model(**batch)\n",
    "        loss = outputs.loss\n",
    "        total_loss += loss.detach().float()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "        lr_scheduler.step()\n",
    "        optimizer.zero_grad()\n",
    "\n",
    "    model.eval()\n",
    "    eval_loss = 0\n",
    "    eval_preds = []\n",
    "    for step, batch in enumerate(tqdm(eval_dataloader)):\n",
    "        batch = {k: v.to(device) for k, v in batch.items()}\n",
    "        with torch.no_grad():\n",
    "            outputs = model(**batch)\n",
    "        loss = outputs.loss\n",
    "        eval_loss += loss.detach().float()\n",
    "        eval_preds.extend(\n",
    "            tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(), skip_special_tokens=True)\n",
    "        )\n",
    "\n",
    "    eval_epoch_loss = eval_loss / len(eval_dataloader)\n",
    "    eval_ppl = torch.exp(eval_epoch_loss)\n",
    "    train_epoch_loss = total_loss / len(train_dataloader)\n",
    "    train_ppl = torch.exp(train_epoch_loss)\n",
    "    print(f\"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "df0c68e0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "accuracy=48.458149779735685 % on the evaluation dataset\n",
      "eval_preds[:10]=['neutral', 'neutral neutral', 'neutral neutral', 'positive positive', 'negative', 'neutral neutral', 'neutral neutral', 'neutral neutral', 'neutral', 'neutral neutral']\n",
      "dataset['validation']['text_label'][:10]=['neutral', 'neutral', 'positive', 'positive', 'negative', 'neutral', 'neutral', 'neutral', 'neutral', 'neutral']\n"
     ]
    }
   ],
   "source": [
    "# print accuracy\n",
    "correct = 0\n",
    "total = 0\n",
    "for pred, true in zip(eval_preds, dataset[\"validation\"][\"text_label\"]):\n",
    "    if pred.strip() == true.strip():\n",
    "        correct += 1\n",
    "    total += 1\n",
    "accuracy = correct / total * 100\n",
    "print(f\"{accuracy=} % on the evaluation dataset\")\n",
    "print(f\"{eval_preds[:10]=}\")\n",
    "print(f\"{dataset['validation']['text_label'][:10]=}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "vscode": {
   "interpreter": {
    "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
